<template>
	<div class="box">
		<div class="sidenav">
			<ul class="group">
				<li v-for="(g, index) in groups" :key="index" @click="select(g)" :class="{
            activate: selected != null && g.groupId == selected.groupId,
          }">
					<group :selected="g"/>
				</li>
			</ul>
		</div>
		<div class="msgbox" id="msgbox">
			<router-view></router-view>
		</div>
	</div>
</template>

<script>
	import group from "./group.vue";
	import request from "../../api/request";
	const { ipcRenderer } = window.require('electron')


	export default {
		name: "box",
		props: {},
		components: {
			group,
		},
		data() {
			return {
				selected: null,
				//   isActivate: selected != null && ,
				groups: [],
			};
		},
		computed: {},
		watch: {},
		async created() {
			await this.loadMsg();
			window.globalEvents.$on("handleBottom", this.handleBottom);
			window.globalEvents.$on("handleMessage", this.handleMessage);
			ipcRenderer.on('msgAvailable',this.handleMessage)
		},
		mounted() {
			// this.select(g[0]);
		},
		methods: {
			async loadMsg() {
				const res = await request.get(
						"api/friends?userId=" + this.$store.state.info.id
				);
				this.groups = res.data.friendsList;
			},
			select(item) {
				this.selected = item;
				this.selected.ranId = new Date().getTime();
				this.$router.push({
					name: "Chat",
					params: this.selected,
				});
			},
			handleBottom(e) {
				setTimeout(() => {
					let msgBox = document.getElementById("msgbox");
					msgBox.scrollTop = msgBox.scrollHeight;
				}, 500);
			},
			handleMessage(event, msgContainer) {
				//消息是userId发个peerId的
				let self = this;
				let typ = msgContainer.type;
				switch (typ) {
					case "user": {
						for (let item of this.groups) {
							if (item.groupId == msgContainer.peerId) {
								item.msgs.push({
									isMe: true,
									content: msgContainer.content,
									time: new Date().getTime(),
								});
							} else if (item.groupId == msgContainer.userId) {
								item.msgs.push({
									isMe: false,
									content: msgContainer.content,
									time: new Date().getTime(),
								});
							}
						}
						break;
					}
				}
				window.globalEvents.$emit("handleBottom");
			},
			extract(content) {
				// parser = new DOMParser();
				// doc = parser.parseFromString(content, "text/html");
				// imgs = doc.getElementsByTagName("img");
				// for (img of imgs) {
				// 	src = img.src;
				// }
			},
		},
	};
</script>
<style scoped>
	ul {
		list-style: none;
		margin: 0 0;
		padding: 0 0;
	}

	.box {
		height: calc(100% - 80px);
	}

	.box .msgbox {
		float: left;
		width: calc(100% - 250px);
		box-sizing: border-box;
		padding-top: 5px;
		height: 100%;
		overflow-y: auto;
		background-color: #f5f5f5;
	}

	.sidenav {
		float: left;
		width: 250px;
		background: #eeeae8;
		height: 100%;
		overflow-y: auto;
	}

	.group li {
		padding: 10px 10px;
	}

	.group .activate {
		background-color: #c9c6c6;
	}
</style>
